#    Copyright 2008, 2009 Tri-County Electric Cooperative, St. Matthews, South Carolina
#    This file is part of COOPGIS.
#    COOPGIS is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#    COOPGIS is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#    You should have received a copy of the GNU General Public License
#    along with COOPGIS.  If not, see <http://www.gnu.org/licenses/>.
#************************BEGIN Add Include Files to Path************************zz
import sys
NeededPaths=['/opt/coopgis/djangoproject/include', '/opt/coopgis/djangoproject']
for path in NeededPaths:
    if(not path in sys.path):
        sys.path.append(path)
#************************END   Add Include Files to Path************************
import application, command, compatibleunit, geography, oms, staker, symbology, unsorted
import COOPGIS_Ajax, COOPGIS_GPS, COOPGIS_Misc, COOPGIS_ReportLab, COOPGIS_String, COOPGIS_Update
import os, csv, shutil, datetime, time, reportlab, djangoproject.settings
from django.contrib.gis.db import models
from django.contrib.gis.geos import *
from django.http import HttpResponse
from django.contrib import admin
import _mysql as mysql


#03/25/2009 CIS TRANSACTION AREA IS IN DEVELOPMENT 
class CISTransactionType(models.Model):
    """CISTransactionType is a lookup table of the possible types a CIS transaction can be,
       for example, Staker, Engineering, etc..."""
    Name=models.CharField(max_length=250)
    Description=models.TextField(null=True, blank=True)
    class Meta:
        db_table=u'coopgiscistransactiontype'
        app_label='djangoproject'


#Sample Transaction of a job:
#2552100000GAGASYSTEM2108PARTNERSOFT                 INTERFACE                   0000002             02003471212800001101029112CLASSIC MANOR BUILDERS INC  0100004081321909010101000000000022SEC LIGHT                                                                                                                                                       000012/31/0812/31/0800/00/0000/00/0000/00/0000/00/0000/00/0000/00/0000/00/0000/00/0000/00/00000007007002000000.0000000000ST      00000000000000000000000000000000000000000000000000000000000000000000000000000000112/31/0800000000000000000000000000000000000000000000000000000070000000000000000/00/0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000712128X
#Sample Transaction of a staking sheet:
#2552200000GAGASYSTEM2108PARTNERSOFT                 INTERFACE                   0000002             020034698382200530/6            100000010G39-15          100000010LS-100          100000010K11             1000000202T              100001600X

class CISTransaction(models.Model):
    """CISTransaction is a table of Transaction Records that either:
       Have been received from the CIS
       Need to be sent to the CIS
       Have been sent to the CIS"""
    Content=models.TextField()
    CISTransactionType=models.ForeignKey('CISTransactionType')
    OutboundIndicator=models.NullBooleanField(null=True, blank=True)
    InboundIndicator=models.NullBooleanField(null=True, blank=True)
    ReceivedDateTime=models.DateTimeField(null=True, blank=True)
    SentDateTime=models.DateTimeField(null=True, blank=True)
    SentIndicator=models.NullBooleanField(null=True, blank=True)
    ProcessedIndicator=models.NullBooleanField(null=True, blank=True)
    objects=models.GeoManager()
    class Meta:
        db_table=u'coopgiscistransaction'
        app_label='djangoproject'
    def Send(self):
        """Send the Transaction to the CIS"""
        pass
    def  Process(self):
        """Apply the Transcation to COOPGIS"""
        pass
    def SendAll(self):
        """Sends all Transactions to the CIS"""
        CISEngineerings = CIS


class CISCompatibleUnit(models.Model):
    """CISCompatibleUnit is a table of Compatible Units that exist in the CIS,
       CompatibleUnit has CISCompatible Unit has a foreign Key"""
    Name=models.CharField(max_length=250, unique=True)
    Description=models.TextField()
    PrefixCode=models.CharField(max_length=250)
    objects=models.GeoManager()
    class Meta:
        db_table=u'coopgisciscompatibleunit'
        app_label='djangoproject'
    def ModifyOrCreate(self, Name, Description='', PrefixCode=''):
        try:
            New=CISCompatibleUnit.objects.get(Name=Name)
            New.Description=Description
            New.PrefixCode=PrefixCode
            New.save()
            return New
        except:
            pass
        New=CISCompatibleUnit()
        New.Name=Name
        New.Description=Description
        New.save()
        return New
    def LoadFromCISVendorFile(self):
        File=open(djangoproject.settings.COOPGISCISVendorCompatibleUnitFileName, 'r')
        Lines=File.readlines()
        File.close()
        for line in Lines:
            if(len(line) < 19):
                continue
            if(not line[:2] == '10'):  #'10' is the code for a Compatible Unit
                continue 
            NewName=line[2:18].strip()  #fixed length field in file from CIS
            NewDescription=line[18:-2]  #strip \r\n
            NewPrefixCode='10'
            New=self.ModifyOrCreate(Name=NewName, Description=NewDescription, PrefixCode=NewPrefixCode)
            






#Some Meter Matching functions....  


def MatchMetersByMapNumber():
    Meters=Assembly.objects.filter(CompatibleUnit__MeterIndicator=True)
    for meter in Meters:
        if(not meter.MeterLocationNumberFromCIS):
            PossibleMatches=OMSCustomer.objects.filter(CalculatedOldMapNumber=meter.OldMapNumber)
            if(PossibleMatches.count() == 1 and len(meter.OldMapNumber) > 3):
                meter.MeterLocationNumberFromCIS=PossibleMatches[0].MapLocation
                print "A Match was found:  " + str(PossibleMatches[0].CalculatedOldMapNumber) + '      ' + str(meter.OldMapNumber)
                meter.save()

def UpdateMeterNumbersFromOMS():
    Meters=djangoproject.models.compatibleunit.Assembly.objects.filter(CompatibleUnit__MeterIndicator=True)
    Updated=0
    NotUpdated=0  
    for meter in Meters:
        LongMapNumber=meter.GetLongMapNumber()
        if(LongMapNumber):
            Matching=djangoproject.models.OMSCustomer.objects.filter(MapLocation=LongMapNumber)
            if(Matching.count()==1 and ((meter.MeterDCSINumber != Matching[0].AMRNumber) or (meter.MeterNumber != Matching[0].MeterNumber))):
                print '********************************************************************************************'
                print 'Change GIS     MeterNumber:  ' + meter.MeterNumber     + '          To:  ' + Matching[0].MeterNumber 
                print 'Change GIS MeterDCSINumber:  ' + meter.MeterDCSINumber + '          To:  ' + Matching[0].AMRNumber
                print '********************************************************************************************'
                meter.MeterDCSINumber=Matching[0].AMRNumber
                meter.MeterNumber=Matching[0].MeterNumber
                meter.save()
                Updated = Updated + 1
                meter.Station.RebuildSymbology()
            else:
                NotUpdated = NotUpdated + 1
    print str(Updated) + " Meters Updated."
    print str(NotUpdated) + " Meters Not Updated"

def GetUnmatchedMeterListFromOMS():
    """Returns a List of Meters that exist in the GIS, but for which matches cannot be foudn in the OMS (which imports data daily from the CIS)"""
    Meters=djangoproject.models.compatibleunit.Assembly.objects.filter(CompatibleUnit__MeterIndicator=True)
    for meter in Meters:
        LongMapNumber=meter.GetLongMapNumber()
        if(LongMapNumber):
            Matching=djangoproject.models.OMSCustomer.objects.filter(MapLocation=LongMapNumber)
            if(Matching.count()==0):
                print 'Unmatched               ' + 'Station Number:  ' + str(meter.Station.id) + ' GIS Map Number:  ' + str(meter.OldMapNumber) + ' Long Map Number:  ' + str(LongMapNumber)
            elif(Matching.count() > 1):
                print 'Multiple Matches Found  ' + 'Station Number:  ' + str(meter.Station.id) + ' GIS Map Number:  ' + str(meter.OldMapNumber) + ' Long Map Number:  ' + str(LongMapNumber)
        else:
            print     'Invalid Map Number:     ' + 'Station Number:  ' + str(meter.Station.id) + ' GIS Map Number:  ' + str(meter.OldMapNumber) + ' Long Map Number:  ' + str(LongMapNumber)
    



def MatchMetersByDCSINumber():
    Meters=Assembly.objects.filter(CompatibleUnit__MeterIndicator=True)
    for meter in Meters:
        if(not meter.MeterLocationNumberFromCIS):
            PossibleMatches=OMSCustomer.objects.filter(CalculatedDCSINumber=meter.MeterDCSINumber)
            if(PossibleMatches.count() == 1 and len(meter.MeterDCSINumber) > 3):
                meter.MeterLocationNumberFromCIS=PossibleMatches[0].MapLocation
                print "A Match was found:  " + str(PossibleMatches[0].MeterNumber) + '      ' + str(meter.MeterDCSINumber)
                meter.save()


def MatchMetersByMeterNumber():
    """Testing as a last resort...."""
    Meters=Assembly.objects.filter(CompatibleUnit__MeterIndicator=True)
    for meter in Meters:
        if(not meter.MeterLocationNumberFromCIS):
            PossibleMatches=OMSCustomer.objects.filter(CalculatedDCSINumber=meter.MeterNumber)
            if(PossibleMatches.count() == 1 and len(meter.MeterNumber) > 3):
                meter.MeterLocationNumberFromCIS=PossibleMatches[0].MapLocation
                print "A Match was found:  " + str(PossibleMatches[0].MeterNumber) + '      ' + str(meter.MeterDCSINumber)
                meter.save()

def MiscMeterCleanupApril2009():
    Meters=Assembly.objects.filter(CompatibleUnit__MeterIndicator=True)
    for meter in Meters:
        if(not meter.MeterLocationNumberFromCIS):
            meter.MeterLocationNumberFromCIS = ''
            meter.save()


